﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : MNY
/// 계      층 : Presentation Layer
/// 프로그램명 : Mny2010r
/// 파  일  명 : Mny2010r.aspx.cs
/// 설      명 : 계정별출납챠트
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-08-04 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.Dac;

using Updms.Mny.Exe;
using Updms.Common.BaseClass;


namespace Updms.Mny
{
	public partial class Mny2010r : PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Mny2010r";
		public static readonly string gs_path_info = "/updms/Mny/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Mny mny = new CommCode.Mny(LANG_SET);

		//검색
		protected string kw1 = "";	//기준년월(시작)
		protected string kw2 = "";	//기준년월(종료)
		protected string kw3 = "";	//구분
		protected string kw4 = "";	//계정

		//메뉴 선택값
		protected string gs_sm = "";

		//합계
		decimal ld_total = 0;

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClass();
			SetAccount();
			SetYearMonth();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion		

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_from_year.SelectedValue +"-"+ ddl_search_from_month.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_from_year.SelectedValue = kw1.Substring(0, 4).ToString();
						ddl_search_from_month.SelectedValue = kw1.Substring(5, 2).ToString();
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = ddl_search_to_year.SelectedValue +"-"+ ddl_search_to_month.SelectedValue;
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						ddl_search_to_year.SelectedValue = kw2.Substring(0, 4).ToString();
						ddl_search_to_month.SelectedValue = kw2.Substring(5, 2).ToString();
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						kw3 = ddl_search_class.SelectedValue;
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						ddl_search_class.SelectedValue = kw3;
					}

					SetAccount();
					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))
					{
						kw4 = WebControlUtil.GetCheckBoxListValue(cbl_search_account);
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						WebControlUtil.SetCheckBoxListValue(cbl_search_account, kw4);
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_from_year.SelectedValue +"-"+ ddl_search_from_month.SelectedValue;
					kw2 = ddl_search_to_year.SelectedValue + "-" + ddl_search_to_month.SelectedValue;
					kw3 = ddl_search_class.SelectedValue;
					kw4 = WebControlUtil.GetCheckBoxListValue(cbl_search_account);
					break;
			}
		}	

		#endregion

		#region 마스터 Method (SetClass, SetAccount, SetYearMonth)

		//구분
		private void SetClass()
		{
			mny.SetClass(ddl_search_class);
		}

		//계정
		private void SetAccount()
		{
			string ls_cd = "";
			DataSet lo_ds = new DataSet();

			ls_cd = ddl_search_class.SelectedValue;
			lo_ds.Merge(global.GetCommUCd("MNY", ls_cd, LANG_SET));

			cbl_search_account.Items.Clear();
			cbl_search_account.DataSource = lo_ds;
			cbl_search_account.DataMember = "UPDMS_COM_CD";
			cbl_search_account.DataTextField = "Text";
			cbl_search_account.DataValueField = "Value";
			cbl_search_account.DataBind();

			if (cbl_search_account.Items.Count > 0)
			{
				cbl_search_account.Items[0].Selected = true;
			}
		}

		//검색조건의 년월설정
		private void SetYearMonth()
		{
			ddl_search_from_year.Items.Clear();
			ddl_search_to_year.Items.Clear();

			int li_f_year = Convert.ToInt32(SEARCH_Y_MIN);
			int li_t_year = Convert.ToInt32(DateUtil.GetYearEx(1, "yyyy"));
			for (int i = li_f_year; i <= li_t_year; i++)
			{
				string ls_year = i.ToString();
				ddl_search_from_year.Items.Add(new ListItem(ls_year, ls_year));
				ddl_search_to_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			SetYearMonth(-12);
		}

		//검색조건의 년월설정 - 기간지정
		private void SetYearMonth(int li_term)
		{
			ddl_search_from_year.SelectedValue = DateUtil.GetMonthEx(li_term, "yyyy"); //x개월전년도
			ddl_search_from_month.SelectedValue = DateUtil.GetMonthEx(li_term, "MM"); //x개월전월
			ddl_search_to_year.SelectedValue = DateUtil.GetYearEx(0, "yyyy"); // 현재년도
			ddl_search_to_month.SelectedValue = DateUtil.GetMonthEx(0, "MM"); // 현재월
		}

		protected void ddl_search_class_SelectedIndexChanged(object sender, EventArgs e)
		{
			SetAccount();
		}

		#endregion

		#region 챠트 (DrawChartLine, DrawChartPie)

		//계정별출납챠트
		private void DrawChartLine()
		{
			int li_line_cnt = 0; //그래프 라인수
			DataPack lo_dp = new DataPack();			

			//초기화
			chart_line.Data.Clear();
			chart_line.Data.Series = WebControlUtil.GetCheckedItemsCount(cbl_search_account);

			lo_dp.AddProperty("ls_base_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_base_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_account", typeof(string));
			
			for (int i=0; i < cbl_search_account.Items.Count; i++ )
			{
				if (cbl_search_account.Items[i].Selected)
				{
					DataSet lo_ds = new DataSet();
					lo_dp["ls_account"] = cbl_search_account.Items[i].Value;
					
					using (Mny2010r_NT _Mny2010r_NT = new Mny2010r_NT())
					{
						lo_ds.Merge(_Mny2010r_NT.GetListByCheckedAccount(lo_dp));
					}
					
					int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_MNY_REPORT");

					for (int j = 0; j < li_count; j++)
					{
						//수동으로 데이터 바인딩
						chart_line.Data[li_line_cnt, j] = DataSetUtil.GetFldInt(lo_ds, "UPDMS_MNY_REPORT", j, "Amount");

						//X축 라벨링
						chart_line.AxisX.Labels[j]
							= "'" + DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", j, "Base_Dt").Replace("-", ".").Substring(2, 5);

						//0은 안보여준다
						chart_line.Points[li_line_cnt, j].PointLabels.Visible = (chart_line.Data[li_line_cnt, j] > 0);
					}

					//시리즈
					chart_line.Series[li_line_cnt].Text = cbl_search_account.Items[i].Text;
					chart_line.Series[li_line_cnt].MarkerShape = ChartFxUtil.markerShape(li_line_cnt);
					
					li_line_cnt = li_line_cnt + 1;
				}//if
			}//for
		}

		//계정별분포도
		private void DrawChartPie(DataSet lo_ds)
		{
			//초기화
			chart_pie.Data.Clear();

			int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_MNY_REPORT");

			for (int i = 0; i < li_count; i++)
			{
				//수동으로 데이터 바인딩
				chart_pie.Data[0, i] = DataSetUtil.GetFldInt(lo_ds, "UPDMS_MNY_REPORT", i, "Amount");

				//X축 라벨링
				chart_pie.AxisX.Labels[i] = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_REPORT", i, "Account_Nm");
			}		
		}

		#endregion

		#region 리스트 (SetTotalAmountByAccount)

		//조회
		private void SetTotalAmountByAccount()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			
			//체크된 계정아이디 추출
			kw4 = WebControlUtil.GetCheckBoxListValue(cbl_search_account);
			
			//검색
			lo_dp.AddProperty("ls_base_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_base_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_class", typeof(string), kw3);
			lo_dp.AddProperty("ls_account", typeof(string), kw4);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Mny2010r_NT _Mny2010r_NT = new Mny2010r_NT())
			{
				lo_ds.Merge(_Mny2010r_NT.GetTotalAmountByAccount(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			DrawChartPie(lo_ds);
		}
		
		#endregion

		#region CRUD (SearchProcess)

		//챠트
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			
			DrawChartLine();
			SetTotalAmountByAccount();

			//즐겨찾기
			string search_condition = "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4);
			ibtn_favorite.Attributes.Add("onclick", "javascript:goFavoriteSearchPage('" + PID + "','" + search_condition + "');return false;");
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);
				
				//합계
				ld_total += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[1].Text = ld_total.ToString("#,###,##0");
				e.Row.Cells[1].Attributes.Add("class", "money");
			}
		}

		#endregion

		#region 버튼이벤트

		//6개월
		protected void sbtn_6_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-5);
		}

		//12개월
		protected void sbtn_12_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-12);
		}

		//전체
		protected void sbtn_all_m_Click(object sender, EventArgs e)
		{
			ddl_search_from_year.SelectedIndex = 0;
			ddl_search_from_month.SelectedIndex = 0;
			ddl_search_to_year.SelectedIndex = ddl_search_to_year.Items.Count - 1;
			ddl_search_to_month.SelectedIndex = ddl_search_to_month.Items.Count - 1;
		}

		//검색
		protected void ibtn_chart_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			kw4 = WebControlUtil.GetCheckBoxListValue(cbl_search_account);

			//검색
			lo_dp.AddProperty("ls_base_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_base_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_class", typeof(string), kw3);
			lo_dp.AddProperty("ls_account", typeof(string), kw4);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Mny2010r_NT _Mny2010r_NT = new Mny2010r_NT())
			{
				lo_ds.Merge(_Mny2010r_NT.GetTotalAmountByAccount(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		#endregion
	}
}
